package com.glsc.ngateway.wordconver.utils;

import com.google.common.util.concurrent.RateLimiter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.validation.constraints.NotBlank;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author xuchang
 */
public class PdfUtil {

    private static final Logger logger = LoggerFactory.getLogger(PdfUtil.class);
    /**
     * 令牌桶
     */
    static RateLimiter rateLimiter = RateLimiter.create(0.2);
    /**
     * 通过页面获取截图并转为pdf
     *
     * @param srcPath
     * @param sessionId
     * @return
     * @throws InterruptedException
     * @throws IOException
     */
    public static File getPdfFromOaUrl(@NotBlank String srcPath, @NotBlank String sessionId, @NotBlank String chromeDriverUrl, @NotBlank String outfileUrl) throws InterruptedException, IOException {
        //
        rateLimiter.acquire();
        // 设置 chromedirver 的存放位置
        System.getProperties().setProperty("webdriver.chrome.driver", chromeDriverUrl);
        ChromeOptions chromeOptions = new ChromeOptions();
        // 设置无头浏览器，这样就不会弹出浏览器窗口，headless模式下，无法另存为PDF，后续排查原因，再使用headless模式
//        chromeOptions.addArguments("--headless");
        // 指定打印机为PDF
        chromeOptions.addArguments("--enable-print-browser");
        //设置静默打印
        chromeOptions.addArguments("--kiosk-printing");
        chromeOptions.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36");
        //指定目录
        String mkdirs = outfileUrl + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        new File(mkdirs).mkdirs();
        //文件名称
        String fileName = "GW_HTML_" + UUID.randomUUID() + ".pdf";
        // 自动保存为PDF文件
        Map<String, Object> prefs = new HashMap<>();
        prefs.put("printing.print_preview_sticky_settings.appState",
                "{\"recentDestinations\":[{\"id\":\"Save as PDF\",\"origin\":\"local\",\"account\":\"\"}],\"selectedDestinationId\":\"Save as PDF\",\"version\":2}");
        prefs.put("savefile.default_directory", mkdirs);
        chromeOptions.setExperimentalOption("prefs", prefs);
        WebDriver webDriver = new ChromeDriver(chromeOptions);
        try {
            //设置超时时间
            webDriver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
            webDriver.manage().timeouts().setScriptTimeout(120, TimeUnit.SECONDS);
//            String urlRequest = host + "/spa/workflow/static4form/index.html?#/main/workflow/req?requestid=" + requestid+"&isprint=1";
            webDriver.get(srcPath);
            //OA的session
            webDriver.manage().addCookie(new Cookie("ecology_JSessionid", sessionId));
            webDriver.manage().addCookie(new Cookie("JSESSIONID", sessionId));
            webDriver.manage().addCookie(new Cookie("__clusterSessionIDCookieName", sessionId));
            Thread.sleep(6000);
            //弹出保存窗口，取消掉
            System.setProperty("java.awt.headless", "false");
//            Screen screen = new Screen();
//            screen.type(Key.ESC);
            // 保存页面为PDF并指定保存路径
            ((ChromeDriver) webDriver).executeScript("document.title=\'" + fileName + "\';");
            ((ChromeDriver) webDriver).executeScript("print();");
            // Wait for the PDF download to complete
            Thread.sleep(2000);
        } finally {
            webDriver.quit();
            logger.info("关闭webDriver");
        }
        // Find the downloaded PDF file and do something with it
        File file = new File(mkdirs + "/" + fileName);
        if (file.exists()) {
            // Do something with the PDF file
            logger.info("保存页面为PDF为" + mkdirs + "/" + fileName);
        } else {
            throw new FileNotFoundException("PDF file not found.");
        }
        return file;
    }

    /**
     * 截图
     */
    public static void addShot(WebDriver webDriver, String outfileUrl) throws IOException, DocumentException {
        //页面截图
        File screenshot = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
        //读取截图
        BufferedImage img = ImageIO.read(screenshot);
        //临时文件夹路径名
        String mkdirs = outfileUrl + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //创建文件夹
        new File(mkdirs).mkdirs();
        File file = new File(mkdirs + "/" + UUID.randomUUID().toString() + ".pdf");
        //创建文件
        file.createNewFile();
        logger.info("创建文件：" + file.getPath());
        FileOutputStream fos = new FileOutputStream(file);
        Document doc = new Document(null, 0, 0, 0, 0);
        try {
            doc.setPageSize(new com.itextpdf.text.Rectangle(img.getWidth(), img.getHeight()));
            Image image = Image.getInstance(screenshot.toURI().toURL());
            //截图写入pdf
            PdfWriter.getInstance(doc, fos);
            doc.open();
            doc.add(image);
        } finally {
            doc.close();
        }
    }
}
